package com.dpj.z_book.filter;

import com.dpj.book.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class SessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        判断是否是登录注册页面，如果是直接放行
        String[] urls={"/w9/user/","/w9/book/","/w9/element-ui/","/w9/js/","/w9/static/","/w9/pages/user/regist.html","/w9/index.html","/w9/pages/user/login.html"};
        HttpServletRequest servletRequest= (HttpServletRequest) request;
        String path = servletRequest.getRequestURI().toString();
        for (String url : urls) {
            if (url.contains(path)) {//找到了，放行
                chain.doFilter(request, response);
                return;
            }
        }
                HttpServletResponse servletResponse= (HttpServletResponse) response;
                User user = (User) servletRequest.getSession().getAttribute("user");
                if(user==null){
                    servletResponse.sendRedirect("/w9/pages/user/login.html");
                }else {
                    chain.doFilter(request,response);
                }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
